<?php


namespace App\Util;


use App\Managers\Admin\AdminLogManager;

class AdminLogUtil
{



    // 添加数据
    public static function created($table,$data)
    {
        list($type , $user_id) = LoginUtil::getAdminMaster();
        if(empty($user_id)) return true;
        $user_type = LoginUtil::getUserClass() ?? '';
        $controller_name = defined('CONTROLLER_NAME') ? \CONTROLLER_NAME : '';
        $module_name =  defined('MODULE_NAME') ? \MODULE_NAME : '';
        $action_name =  defined('ACTION_NAME') ? \ACTION_NAME : '';
        $type = 'create';
        $data = collect($data);
        $content =  json_encode($data,JSON_UNESCAPED_UNICODE) ;
        /** @var AdminLogManager $app */
        $app = app(AdminLogManager::class);
        $app->setData(compact('user_id', 'user_type', 'type', 'content','controller_name','module_name','action_name','table'));
        return $app->save();
    }


    //修改数据
    public static function updated($table, $sources, $data)
    {

        list($type , $user_id) = LoginUtil::getAdminMaster();
        if(empty($user_id)) return true;
        $user_type = LoginUtil::getUserClass() ?? '';
        $controller_name = defined('CONTROLLER_NAME') ? \CONTROLLER_NAME : '';
        $module_name =  defined('MODULE_NAME') ? \MODULE_NAME : '';
        $action_name =  defined('ACTION_NAME') ? \ACTION_NAME : '';
//        $created_at = $updated_at = date('Y-m-d H:i:s');
        $type = 'update';
        $content = "";
        foreach ($data as $key=>$value){
            $origin = data_get($sources, $key,'');
            $origin = is_string($origin)?:collect($origin)->toJson();
            if ($key === 'updated_at' || $origin == $value) continue;
            $content .= "{$key}: {$origin} => {$value} \r\n";
        }

        /** @var AdminLogManager $app */
        $app = app(AdminLogManager::class);
        $app->setData(compact('user_id', 'user_type', 'type', 'content','controller_name','module_name','action_name','table'));
        return $app->save();
    }


    //删除数据
    public static function deleted($table,$sources)
    {

        $sources = collect($sources);
        list($type , $user_id) = LoginUtil::getAdminMaster();
        if(empty($user_id)) return true;
        $user_type = LoginUtil::getUserClass() ?? '';
        $controller_name = defined('CONTROLLER_NAME') ? \CONTROLLER_NAME : '';
        $module_name =  defined('MODULE_NAME') ? \MODULE_NAME : '';
        $action_name =  defined('ACTION_NAME') ? \ACTION_NAME : '';
//        $created_at = $updated_at = date('Y-m-d H:i:s');
        $type = 'delete';
        $content =  json_encode($sources,JSON_UNESCAPED_UNICODE) ;
        /** @var AdminLogManager $app */
        $app = app(AdminLogManager::class);
        $app->setData(compact('user_id', 'user_type', 'type', 'content','controller_name','module_name','action_name','table'));
        return $app->save();

    }
}
